package com.zhihaoliang.busEncy

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.gyf.immersionbar.ImmersionBar
import com.zhihaoliang.busEncy.adapter.BusiLeftAdapter
import com.zhihaoliang.busEncy.model.BusiLeftBean
import com.zhihaoliang.busEncy.model.list.FloorPager
import kotlinx.android.synthetic.main.activity_main.*

val LEFT_TXT = listOf(
    "热门推荐", "流量业务", "语言业务", "红包业务", "国际/港澳台", "5G/4G套餐", "我要办卡",
    "宽度家庭", "政企业务", "生活会员", "娱乐会员", "教育会员", "话费购物", "优惠业务", "更多业务", "功能设置"
)

val ANCHOR_TXT = mutableListOf("锚点占位1", "锚点占位2", "锚点占位3", "锚点占位4", "锚点占位5", "锚点占位6", "锚点占位7", "锚点占位8")

const val TAG = "~~~~~"

class MainActivity : AppCompatActivity() {

    private var lastTag: String = ""

    private lateinit var leftAdapter: BusiLeftAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
        setStatusBar()
    }

    private fun initView() {
        leftAdapter = BusiLeftAdapter { item ->
            if (item.typeID == null) return@BusiLeftAdapter
            leftAdapter.updateListIndex(item)
            initFragment(item)
        }
        rvLeft.adapter = leftAdapter
        initData()
        if (leftAdapter.listData.size > 0) {
            initFragment(leftAdapter.listData[0])
        }

    }

    private fun initFragment(item: BusiLeftBean) {
        val tag = item.typeID ?: return
        val from = supportFragmentManager.findFragmentByTag(lastTag)
        val to = supportFragmentManager.findFragmentByTag(tag) ?: BusiLeftFragment.newInstance(tag)
        switchFragment(from, to, tag)
        lastTag = tag
    }

    private fun initData() {
        val listData: MutableList<BusiLeftBean> = ArrayList()
        for (index in LEFT_TXT.indices) {
            listData.add(
                BusiLeftBean(
                    busiName = LEFT_TXT[index],
                    typeID = "$index",
                    isSelect = index != 0,
                    isShowTop = index == 1
                )
            )
        }
        leftAdapter.updateListData(listData)

    }

    private fun setStatusBar() {
        val immersionBar = ImmersionBar.with(this).keyboardEnable(true)
            .statusBarDarkFont(true)
            .fitsSystemWindows(true)
            .navigationBarColor(R.color.white)
            .statusBarColor(R.color.white)
        immersionBar.init()
    }


    private fun switchFragment(from: Fragment?, to: Fragment, tag: String) {
        if (from == to) return
        val ft = supportFragmentManager.beginTransaction()
        if (to.isAdded) {
            if (from != null) {
                ft.hide(from)
            }
            ft.show(to).commit()
            return
        }

        if (from != null) ft.hide(from)
        ft.add(R.id.fragment_container, to, tag).commit()
    }
}